package xin.fsqr520.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import io.netty.buffer.PoolSubpageMetric;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xin.fsqr520.project.domain.po.BaseException;
import xin.fsqr520.project.domain.po.Post;
import xin.fsqr520.project.domain.po.PostLike;
import xin.fsqr520.project.mapper.PostLikeMapper;
import xin.fsqr520.project.mapper.PostMapper;
import xin.fsqr520.project.service.IPostLikeService;
import xin.fsqr520.project.service.IPostService;

@Service
public class PostLikeServiceImpl extends ServiceImpl<PostLikeMapper, PostLike> implements IPostLikeService {
    @Autowired
    private PostLikeMapper postLikeMapper;

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private IPostService postService;




    @Override
    @Transactional
    public int likeOrUnlike(Long userId, Long postId, Boolean flag) {
        //首先记录添加或者删除改一下
        //先看看帖子在不在
//        long count = postService.count(new LambdaQueryWrapper<Post>().eq(Post::getPostId, postId));
        if (flag) {//当前是要点赞
            //先看看点赞记录在不在
            long count = this.count(new LambdaQueryWrapper<PostLike>()
                    .eq(PostLike::getPostId, postId).eq(PostLike::getUserId, userId));
            if (count == 1) throw new BaseException("点赞失败 当前帖子已点赞!");
            PostLike postLike = PostLike.builder().postId(postId).userId(userId).build();
            //插入点赞记录
            int i = postLikeMapper.insert(postLike);
            int j = postMapper.addLike(postId, 1);
            if (i == 1 && j == 1) return 1;
            return 0;
        } else {//当前是要取消
            PostLike postLike = postLikeMapper.selectOne(new LambdaQueryWrapper<PostLike>()
                    .eq(PostLike::getPostId, postId).eq(PostLike::getUserId, userId));
            if (postLike == null) throw new BaseException("取消点赞失败 当前帖子尚未点赞!");
            //删了记录
            int i = postLikeMapper.deleteById(postLike.getId());
            int j = postMapper.addLike(postId, -1);
            if (i == 1 && j == 1) return 1;
            return 0;
        }
    }
}
